<template>
  <a-modal
    v-model:open="visible"
    :title="isEditing ? '编辑关系' : '关系详情'"
    :width="600"
    :footer="null"
    @cancel="handleCancel"
  >
    <div v-if="relationship" class="relationship-modal">
      <!-- 关系基本信息 -->
      <a-descriptions 
        v-if="!isEditing" 
        :column="2" 
        bordered
        size="small"
        class="relationship-descriptions"
      >
        <a-descriptions-item label="关系ID">
          {{ relationship.id }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ formatDate(relationship.createdAt) }}
        </a-descriptions-item>
        <a-descriptions-item label="源实体">
          <a-tag :color="getEntityTypeColor(sourceEntity?.type)">
            {{ sourceEntity?.name }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="目标实体">
          <a-tag :color="getEntityTypeColor(targetEntity?.type)">
            {{ targetEntity?.name }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="关系类型">
          <a-tag :color="getRelationshipTypeColor(relationship.relationshipType)">
            {{ getRelationshipTypeLabel(relationship.relationshipType) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="关系强度">
          <a-progress 
            :percent="relationship.strength * 100" 
            size="small"
            :stroke-color="getStrengthColor(relationship.strength)"
          />
        </a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">
          {{ relationship.description || '暂无描述' }}
        </a-descriptions-item>
        <a-descriptions-item label="最后更新">
          {{ formatDate(relationship.updatedAt) }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 编辑表单 -->
      <a-form
        v-else
        ref="formRef"
        :model="editForm"
        :rules="formRules"
        layout="vertical"
        class="relationship-form"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="源实体" name="sourceEntityId">
              <a-select
                v-model:value="editForm.sourceEntityId"
                placeholder="选择源实体"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="entity in availableEntities"
                  :key="entity.id"
                  :value="entity.id"
                >
                  <a-tag :color="getEntityTypeColor(entity.type)" size="small">
                    {{ entity.name }}
                  </a-tag>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标实体" name="targetEntityId">
              <a-select
                v-model:value="editForm.targetEntityId"
                placeholder="选择目标实体"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="entity in availableEntities"
                  :key="entity.id"
                  :value="entity.id"
                >
                  <a-tag :color="getEntityTypeColor(entity.type)" size="small">
                    {{ entity.name }}
                  </a-tag>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="关系类型" name="relationshipType">
              <a-select
                v-model:value="editForm.relationshipType"
                placeholder="选择关系类型"
              >
                <a-select-option
                  v-for="type in relationshipTypes"
                  :key="type.value"
                  :value="type.value"
                >
                  <a-tag :color="type.color" size="small">
                    {{ type.label }}
                  </a-tag>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关系强度" name="strength">
              <a-slider
                v-model:value="editForm.strength"
                :min="0"
                :max="1"
                :step="0.1"
                :tooltip-formatter="(value: number) => `${(value * 100).toFixed(0)}%`"
              />
              <div class="strength-display">
                强度: {{ (editForm.strength * 100).toFixed(0) }}%
              </div>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="editForm.description"
            placeholder="请输入关系描述"
            :rows="3"
            show-count
            :maxlength="500"
          />
        </a-form-item>
      </a-form>

      <!-- 关系统计信息 -->
      <div v-if="!isEditing && relationshipStats" class="relationship-stats">
        <a-divider>关系统计</a-divider>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-statistic
              title="交互次数"
              :value="relationshipStats.interactionCount"
              :value-style="{ color: '#1890ff' }"
            />
          </a-col>
          <a-col :span="8">
            <a-statistic
              title="平均响应时间"
              :value="relationshipStats.avgResponseTime"
              suffix="ms"
              :value-style="{ color: '#52c41a' }"
            />
          </a-col>
          <a-col :span="8">
            <a-statistic
              title="协作成功率"
              :value="relationshipStats.successRate * 100"
              suffix="%"
              :precision="1"
              :value-style="{ color: '#722ed1' }"
            />
          </a-col>
        </a-row>
      </div>

      <!-- 关系历史 -->
      <div v-if="!isEditing && relationshipHistory?.length" class="relationship-history">
        <a-divider>关系历史</a-divider>
        <a-timeline size="small">
          <a-timeline-item
            v-for="item in relationshipHistory"
            :key="item.id"
            :color="getHistoryItemColor(item.type)"
          >
            <template #dot>
              <component :is="getHistoryIcon(item.type)" />
            </template>
            <div class="history-item">
              <div class="history-title">{{ item.title }}</div>
              <div class="history-description">{{ item.description }}</div>
              <div class="history-time">{{ formatDate(item.timestamp) }}</div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-space>
          <a-button @click="handleCancel">
            取消
          </a-button>
          <a-button v-if="!isEditing" @click="startEdit" type="primary">
            编辑
          </a-button>
          <a-button v-if="!isEditing" @click="handleDelete" danger>
            删除
          </a-button>
          <a-button v-if="isEditing" @click="handleSave" type="primary" :loading="saving">
            保存
          </a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { 
  EditOutlined, 
  DeleteOutlined, 
  PlusOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons-vue'
import { networkApi } from '@/api/network'
import { lifeEntityApi } from '@/api/lifeEntity'
import type { LifeEntityRelationship, LifeEntity } from '@/api/types'

interface RelationshipStats {
  interactionCount: number
  avgResponseTime: number
  successRate: number
}

interface RelationshipHistoryItem {
  id: string
  type: 'created' | 'updated' | 'interaction' | 'conflict'
  title: string
  description: string
  timestamp: string
}

interface Props {
  relationship: LifeEntityRelationship | null
  visible: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'updated', relationship: LifeEntityRelationship): void
  (e: 'deleted', relationshipId: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const isEditing = ref(false)
const saving = ref(false)
const formRef = ref()
const availableEntities = ref<LifeEntity[]>([])
const relationshipStats = ref<RelationshipStats | null>(null)
const relationshipHistory = ref<RelationshipHistoryItem[]>([])

// 编辑表单
const editForm = ref({
  sourceEntityId: '',
  targetEntityId: '',
  relationshipType: '',
  strength: 0.5,
  description: ''
})

// 表单验证规则
const formRules = {
  sourceEntityId: [
    { required: true, message: '请选择源实体' }
  ],
  targetEntityId: [
    { required: true, message: '请选择目标实体' }
  ],
  relationshipType: [
    { required: true, message: '请选择关系类型' }
  ],
  strength: [
    { required: true, message: '请设置关系强度' }
  ]
}

// 关系类型选项
const relationshipTypes = [
  { value: 'COLLABORATION', label: '协作', color: '#52c41a' },
  { value: 'COMPETITION', label: '竞争', color: '#f5222d' },
  { value: 'DEPENDENCY', label: '依赖', color: '#1890ff' },
  { value: 'FUSION', label: '融合', color: '#722ed1' },
  { value: 'COMMUNICATION', label: '通信', color: '#fa8c16' },
  { value: 'INHERITANCE', label: '继承', color: '#13c2c2' }
]

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const sourceEntity = computed(() => {
  if (!props.relationship) return null
  return availableEntities.value.find(e => e.id === props.relationship!.sourceEntityId)
})

const targetEntity = computed(() => {
  if (!props.relationship) return null
  return availableEntities.value.find(e => e.id === props.relationship!.targetEntityId)
})

// 方法
const handleCancel = () => {
  visible.value = false
  isEditing.value = false
  resetForm()
}

const startEdit = () => {
  if (!props.relationship) return
  
  editForm.value = {
    sourceEntityId: props.relationship.sourceEntityId,
    targetEntityId: props.relationship.targetEntityId,
    relationshipType: props.relationship.relationshipType,
    strength: props.relationship.strength,
    description: props.relationship.description || ''
  }
  
  isEditing.value = true
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    
    const updatedRelationship = await networkApi.updateRelationship(
      props.relationship!.id,
      editForm.value
    )
    
    message.success('关系更新成功')
    emit('updated', updatedRelationship)
    isEditing.value = false
    visible.value = false
  } catch (error) {
    message.error('关系更新失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个关系吗？此操作不可恢复。',
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await networkApi.deleteRelationship(props.relationship!.id)
        message.success('关系删除成功')
        emit('deleted', props.relationship!.id)
        visible.value = false
      } catch (error) {
        message.error('关系删除失败')
      }
    }
  })
}

const resetForm = () => {
  editForm.value = {
    sourceEntityId: '',
    targetEntityId: '',
    relationshipType: '',
    strength: 0.5,
    description: ''
  }
}

const loadAvailableEntities = async () => {
  try {
    const entities = await lifeEntityApi.getList({ size: 1000 })
    availableEntities.value = entities.content
  } catch (error) {
    message.error('加载实体列表失败')
  }
}

const loadRelationshipStats = async (relationshipId: string) => {
  try {
    // 模拟加载关系统计数据
    relationshipStats.value = {
      interactionCount: Math.floor(Math.random() * 1000) + 100,
      avgResponseTime: Math.floor(Math.random() * 500) + 50,
      successRate: Math.random() * 0.3 + 0.7
    }
  } catch (error) {
    console.error('加载关系统计失败:', error)
  }
}

const loadRelationshipHistory = async (relationshipId: string) => {
  try {
    // 模拟加载关系历史数据
    relationshipHistory.value = [
      {
        id: '1',
        type: 'created',
        title: '关系建立',
        description: '两个生命体建立了新的关系连接',
        timestamp: new Date(Date.now() - 86400000 * 7).toISOString()
      },
      {
        id: '2',
        type: 'interaction',
        title: '协作交互',
        description: '成功完成了一次协作任务',
        timestamp: new Date(Date.now() - 86400000 * 3).toISOString()
      },
      {
        id: '3',
        type: 'updated',
        title: '关系强化',
        description: '关系强度从60%提升到80%',
        timestamp: new Date(Date.now() - 86400000).toISOString()
      }
    ]
  } catch (error) {
    console.error('加载关系历史失败:', error)
  }
}

// 辅助函数
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getEntityTypeColor = (type?: string) => {
  const colors: Record<string, string> = {
    CORPORATE: '#1890ff',
    URBAN: '#52c41a',
    CONCEPTUAL: '#722ed1',
    INDIVIDUAL: '#fa8c16',
    HYBRID: '#eb2f96',
    SYSTEM: '#13c2c2'
  }
  return colors[type || ''] || '#666'
}

const getRelationshipTypeColor = (type: string) => {
  const typeConfig = relationshipTypes.find(t => t.value === type)
  return typeConfig?.color || '#666'
}

const getRelationshipTypeLabel = (type: string) => {
  const typeConfig = relationshipTypes.find(t => t.value === type)
  return typeConfig?.label || type
}

const getStrengthColor = (strength: number) => {
  if (strength >= 0.8) return '#52c41a'
  if (strength >= 0.6) return '#1890ff'
  if (strength >= 0.4) return '#fa8c16'
  return '#f5222d'
}

const getHistoryItemColor = (type: string) => {
  const colors: Record<string, string> = {
    created: '#52c41a',
    updated: '#1890ff',
    interaction: '#722ed1',
    conflict: '#f5222d'
  }
  return colors[type] || '#666'
}

const getHistoryIcon = (type: string) => {
  const icons: Record<string, any> = {
    created: PlusOutlined,
    updated: EditOutlined,
    interaction: CheckCircleOutlined,
    conflict: ExclamationCircleOutlined
  }
  return icons[type] || ClockCircleOutlined
}

const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().includes(input.toLowerCase())
}

// 监听关系变化
watch(() => props.relationship, (newRelationship) => {
  if (newRelationship) {
    loadRelationshipStats(newRelationship.id)
    loadRelationshipHistory(newRelationship.id)
  }
}, { immediate: true })

// 监听弹窗显示
watch(() => props.visible, (visible) => {
  if (visible) {
    loadAvailableEntities()
  }
})
</script>

<style scoped>
.relationship-modal {
  max-height: 70vh;
  overflow-y: auto;
}

.relationship-descriptions {
  margin-bottom: 24px;
}

.relationship-form {
  margin-bottom: 24px;
}

.strength-display {
  text-align: center;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.relationship-stats {
  margin-bottom: 24px;
}

.relationship-history {
  margin-bottom: 24px;
}

.history-item {
  padding-left: 8px;
}

.history-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.history-description {
  color: #666;
  font-size: 12px;
  margin-bottom: 4px;
}

.history-time {
  color: #999;
  font-size: 11px;
}

.modal-actions {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>